/************************************************************************
 *   IRC - Internet Relay Chat
 *   Copyright (C) 2005 Elias Shtift
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 1, or (at your option)
 *   any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *   $Id: $
 */

#include "stdinc.h"
#include "client.h"
#include "send.h"
#include "modules.h"
#include "handlers.h"
#include "translate.h"
#include "irc_string.h"
#include "ircd.h"

static void m_codepage(struct Client *, struct Client *, int, char *[]);

struct Message codepage_msgtab = {
  "CODEPAGE", 0, 0, 0, 1, MFLG_SLOW, 0,
  { m_unregistered, m_codepage, m_ignore, m_ignore, m_codepage, m_ignore }
};

#ifndef STATIC_MODULES
void
_modinit(void)
{
  mod_add_cmd(&codepage_msgtab);
}

void
_moddeinit(void)
{
  mod_del_cmd(&codepage_msgtab);
}

const char *_version = "$Revision: 1 $";
#endif

/*
 * m_codepage
 *      parv[0] = sender prefix
 *      parv[1] = parameter
 */
static void
m_codepage(struct Client *client_p, struct Client *source_p,
       int parc, char *parv[])
{
  char cp_list[CHARSETLEN * 11];
  struct Codepage *cp = codepages;
  int i;

  if (parc < 2 && MyConnect(source_p))
  {
    sendto_one(source_p, ":%s NOTICE %s :For change codepage on fly, please use /CODEPAGE charset, for listing charsets /CODEPAGE list",
               me.name, source_p->name);
    return;
  }

  if (!irccmp(parv[1], "LIST"))
  {
    strcpy(cp_list, ": CP1251, ");

    for (i = 0; i < 10 && cp; i++, cp = cp->next)
    {
      strcat(cp_list, cp->name);
      if (cp->next)
        strcat(cp_list, ", ");
    }

    sendto_one(source_p, ":%s NOTICE %s :Our IRC server support following codepages %s.",
               me.name, source_p->name, cp_list);
    return;
  }
  else
  {
    cp = translate_codepage_find_byname(parv[1]);

    if (cp)
    {
      source_p->localClient->cp = cp;
      sendto_one(source_p, ":%s NOTICE %s :Your codepage set to %s charset",
                 me.name, source_p->name, cp->name);
    }
    else if (!irccmp(parv[1], "CP1251"))
    {
      source_p->localClient->cp = NULL;
      sendto_one(source_p, ":%s NOTICE %s :Your codepage set to %s charset",
                 me.name, source_p->name, "CP1251");
    }
    else
      sendto_one(source_p, ":%s NOTICE %s :Unknown codepage %s",
                 me.name, source_p->name, parv[1]);
  }
}
